package decisionLines.control;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import decisionLines.model.DecisionLinesEvent;
import decisionLines.model.Edge;
import decisionLines.view.Application;

/**
 * DrawEdgeController Class
 */
public class DrawEdgeController extends MouseAdapter {
	Application view;
	DecisionLinesEvent event;
	
	/**
	 * Constructor: Create the DrawEdgeController class
	 * @param dle - DecisionLinesEvent, the DecisionLinesEvent class to be used in controlling objects
	 * @param app - Application, the physical object being affected
	 */
	public DrawEdgeController(DecisionLinesEvent dle, Application app){
		this.view = app;
		this.event = dle;
	}
	
	/** 
	 * Detect the mouse pressed and get the click location
	 * @param me - MouseEvent
	 */
	@Override
	public void mousePressed(MouseEvent me){
		this.act(me.getX(),me.getY());
	}
	
	/** 
	 * Method: Using the mouse click location, add the edge to the model and tell the panel to update with the edge
	 * @param x - The X location
	 * @param y - The Y location
	 */
	public void act(int x, int y){
		if (!event.isReady()){
			System.out.println("All choices must be entered prior to placing an edge.");
			return;
		}
		
		// ignore any clicks outside the boundaries
		if(x < view.getDrawingCanvas().lineXlocation(0) ||
				x > view.getDrawingCanvas().lineXlocation(event.getNumChoices()-1) ||
				y < view.getDrawingCanvas().lineYlocation(0) ||
				y > (view.getDrawingCanvas().lineYlocation(0) + view.getDrawingCanvas().lineHeight(0))){
			return;
		}
		
		// compare click location to line locations to determine which lines to associate with edge
		for (int i = 0; i < event.getNumChoices(); i++){
			if (x > view.getDrawingCanvas().lineXlocation(i) && x < view.getDrawingCanvas().lineXlocation(i+1)){
				// add the edge only if all NxM edges have not yet been added
				if (!event.isDone()) {
					Edge edge = new Edge(i,y,i+1);
					boolean edgeAdded = event.addEdge(edge);
					System.out.println("Edge (" + edgeAdded + "): " + edge.getLeft() + ", " + edge.getHeight() + ", " + edge.getRight());
				}
				// if all N x M edges have been added, prioritize the choices and display them in prioritized order
				if (event.isDone()){
					System.out.println("DONE!");
					String[] prioritized = event.prioritizedChoices();
					for (int j = 0; j < prioritized.length; j++){
						System.out.print(prioritized[j] + ", ");
					}
					System.out.println("");
				}
				view.redraw();
				return;
			}
		}
	}
}
